package com.lc.luzhengtang.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.icu.text.DecimalFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.RefundListAdapter2;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.RefundBean;
import com.lc.luzhengtang.bean.VerificationCodeBean;
import com.lc.luzhengtang.conn.ConnRefundMoney;
import com.lc.luzhengtang.conn.ConnRefuse_Submit;
import com.lc.luzhengtang.conn.ConnVerificationCode2;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.view.FullyLinearLayoutManager;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilMatches;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lc.luzhengtang.R.id.checkbox_invest;
import static com.lc.luzhengtang.R.id.editText_phone;

/**
 * Created by Administrator on 2017/6/28.
 */

public class RefundActivity extends BaseActivity implements com.lc.luzhengtang.interfaces.NoticeActivity<Integer> {
    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    @BindView(R.id.textView5)
    TextView textView5;
    @BindView(R.id.img_tuikuan)
    ImageView imgTuikuan;
    @BindView(R.id.layout_tukuan)
    LinearLayout layoutTukuan;
    @BindView(R.id.img_quane)
    ImageView imgQuane;
    @BindView(R.id.layout_quane)
    LinearLayout layoutQuane;
    @BindView(R.id.text_money)
    TextView textMoney;

    @BindView(R.id.editText_code)
    EditText editTextCode;
    @BindView(R.id.text_sendbtn)
    TextView textSendbtn;
    @BindView(R.id.edit_pwd)
    EditText editPwd;
    @BindView(R.id.edit_reason)
    EditText editReason;
    @BindView(checkbox_invest)
    CheckBox checkboxInvest;
    @BindView(R.id.notice_invest)
    TextView noticeInvest;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.text_submit)
    TextView textSubmit;
    @BindView(R.id.text_order_text)
    TextView textOrderText;
    @BindView(R.id.layout_tuikuan)
    LinearLayout layoutTuikuan;
    @BindView(R.id.editText_phone)
    EditText editTextPhone;
    @BindView(R.id.img_arrow)
    ImageView imgArrow;
    private String ordersn;
    RefundListAdapter2 refundListAdapter2;

    String text_money;

    String text_money2;
    private PopupWindow popWindow;
    String type = "1";
    String state;
    String aggrement = "0";
    private CountDownTimer countTime = new CountDownTimer(61000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {

            if (!isFinishing()) {
                textSendbtn.setText(millisUntilFinished / 1000 + "s重新获取");
            }
        }

        @Override
        public void onFinish() {

            if (!isFinishing()) {
                textSendbtn.setText("重新获取");
                textSendbtn.setEnabled(true);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund);
        ButterKnife.bind(this);
        ordersn = getIntent().getStringExtra("ordersn");
        recyclerView.setLayoutManager(new FullyLinearLayoutManager(RefundActivity.this));
        recyclerView.setNestedScrollingEnabled(false);
//        checkbox_invest
        checkboxInvest.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    aggrement = "1";
                } else {
                    aggrement = "0";
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        getRefundData();
    }

    public void getRefundData() {
        new ConnRefundMoney(ordersn, new AsyCallBack<RefundBean>() {
            @Override
            public void onStart(int type) throws Exception {
                showLoading();
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, RefundBean refundBean) throws Exception {
                super.onSuccess(toast, type, o, refundBean);
                textMoney.setText("¥" + refundBean.getData().getTotal());
                textOrderText.setText(refundBean.getData().getStsing());
                refundListAdapter2 = new RefundListAdapter2(refundBean.getGoodslist());
                recyclerView.setAdapter(refundListAdapter2);
                text_money2 = refundBean.getData().getTotal();
                text_money = refundBean.getData().getTotal();
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                dismissLoading();
            }
        }

        ).execute(RefundActivity.this, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @OnClick({R.id.img_news, R.id.layout_title, R.id.textView5, R.id.img_tuikuan, R.id.layout_tukuan, R.id.img_quane, R.id.layout_quane, R.id.text_money, editText_phone, R.id.editText_code, R.id.text_sendbtn, R.id.edit_pwd, R.id.edit_reason, R.id.notice_invest, R.id.text_submit, R.id.layout_tuikuan, R.id.img_arrow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.layout_title:
                break;
            case R.id.textView5:
                showPopupWindow(layoutTuikuan);
                break;
            case R.id.img_tuikuan:
                state = "1";
                imgTuikuan.setBackground(getResources().getDrawable(R.mipmap.checkboxselected));
                imgQuane.setBackground(getResources().getDrawable(R.mipmap.checkboxunselected));
                break;
            case R.id.layout_tukuan:
                break;
            case R.id.img_quane:
                state = "2";
                imgTuikuan.setBackground(getResources().getDrawable(R.mipmap.checkboxunselected));
                imgQuane.setBackground(getResources().getDrawable(R.mipmap.checkboxselected));
                break;
            case R.id.layout_quane:
                break;
            case R.id.text_money:
                break;
            case editText_phone:
                break;
            case R.id.editText_code:
                break;
            case R.id.text_sendbtn:
                if (TextUtils.isEmpty(editTextPhone.getText().toString().trim())) {
                    LovelyToast.makeText(RefundActivity.this, "用户手机号不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (editTextPhone.getText().toString().trim().length() < 11) {
                    LovelyToast.makeText(RefundActivity.this, "手机号不能小于11位", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!UtilMatches.checkMobile(editTextPhone.getText().toString())) {
                    LovelyToast.makeText(RefundActivity.this, "请输入正确的手机号", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    // UtilToast.show(RegisterActivity.this, "请输入正确的手机号");
                } else {
                    getVerificationCode();
                }
                break;
            case R.id.edit_pwd:
                break;
            case R.id.edit_reason:
                break;
            case R.id.notice_invest:
                startActivity(new Intent(RefundActivity.this, TuiKuanWebActivity.class));

                break;
            case R.id.text_submit:

                //提交申请退款
                if (TextUtils.isEmpty(type)) {
                    LovelyToast.makeText(RefundActivity.this, "请选择退款类型", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(state)) {
                    LovelyToast.makeText(RefundActivity.this, "请选择退款路线", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(editTextPhone.getText().toString())) {
                    LovelyToast.makeText(RefundActivity.this, "手机号不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!UtilMatches.checkMobile(editTextPhone.getText().toString())) {
                    LovelyToast.makeText(RefundActivity.this, "手机号输入格式不对", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(editTextCode.getText().toString().trim())) {
                    LovelyToast.makeText(RefundActivity.this, "验证码不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!editTextCode.getText().toString().equals(myCode)) {
                    LovelyToast.makeText(RefundActivity.this, "验证码不正确", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(editPwd.getText().toString().trim())) {
                    LovelyToast.makeText(RefundActivity.this, "请输入支付密码", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(editReason.getText().toString())) {
                    LovelyToast.makeText(RefundActivity.this, "请输入退款原因", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (aggrement.equals("0")) {
                    LovelyToast.makeText(RefundActivity.this, "请阅读并履行投资须知", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    submitTuikuan();
                }
//            editText_code


                break;

            case R.id.layout_tuikuan:
                showPopupWindow(layoutTuikuan);

                break;
            case R.id.img_arrow:
                showPopupWindow(layoutTuikuan);
                break;
        }
    }


    private void showPopupWindow(View parent) {
        if (popWindow == null) {
    /*        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_01, null)));*/
//            ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) convertView);
            View view = ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) LayoutInflater.from(this).inflate(R.layout.dialog_tuikuan, null));

            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        LinearLayout layout_quane = (LinearLayout) view.findViewById(R.id.layout_quane);
        final ImageView img_quane = (ImageView) view.findViewById(R.id.img_quane);
        final ImageView img_bufen = (ImageView) view.findViewById(R.id.img_bufen);

        layout_quane.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = "1";
//                textView5
                textView5.setText("全额退款");
                img_quane.setImageResource(R.mipmap.checkboxselected);
                img_bufen.setImageResource(R.mipmap.checkboxunselected);
                popWindow.dismiss();
                text_money = text_money2;
                textMoney.setText("¥"+text_money);
            }
        });
        LinearLayout layout_bufen = (LinearLayout) view.findViewById(R.id.layout_bufen);
        layout_bufen.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                type = "2";
                textView5.setText("部分退款");
                img_quane.setImageResource(R.mipmap.checkboxunselected);
                img_bufen.setImageResource(R.mipmap.checkboxselected);
                popWindow.dismiss();
             /*   String price_CNY ="5";
                Double cny = Double.parseDouble(price_CNY);//转换成Double
                DecimalFormat df = new DecimalFormat("0.00");//格式化
                String CNY = df.format(cny);
                System.out.println(CNY);//5.00*/


                int a = Double.valueOf(text_money).intValue() / 10;
//                text_money = String.valueOf(a);
                Double cny = Double.parseDouble(String.valueOf(a));//转换成Double
                DecimalFormat df = new DecimalFormat("0.00");//格式化
                String CNY = df.format(cny);
                text_money = CNY;

                textMoney.setText("¥"+text_money);
            }
        });

    }

    String myCode;


    public void getVerificationCode() {
        new ConnVerificationCode2(editTextPhone.getText().toString().trim(), "tong", BaseApplication.basePreferences.readUid(), new AsyCallBack<VerificationCodeBean>() {

            @Override
            public void onSuccess(String toast, int type, Object o, VerificationCodeBean registerBean) throws Exception {
/*
                LovelyToast.makeText(RegisterActivity.this, ConnVerificationCode.TOAST, 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/
                super.onSuccess(toast, type, o, registerBean);
                if (registerBean.getCode() == 200) {
                    countTime.start();
//                finish();myCode=registerBean.getData().getCode();
                    LovelyToast.makeText(RefundActivity.this, registerBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    myCode = registerBean.getData().getCode() + "";
                } else {
                    LovelyToast.makeText(RefundActivity.this, registerBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
               /* LovelyToast.makeText(RegisterActivity.this, ConnVerificationCode.TOAST, 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/
                textSendbtn.setEnabled(false);
                textSendbtn.setText("获取验证码");

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }


        ).execute(this);
    }


    //    editText_phone   edit_reason  edit_pwd
    public void submitTuikuan() {
        new ConnRefuse_Submit(BaseApplication.basePreferences.readUid(), editTextPhone.getText().toString().trim(), editReason.getText().toString().trim(),
                text_money, state, type, ordersn, editPwd.getText().toString(), new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                if (commenBean.getCode() == 200) {
                    LovelyToast.makeText(RefundActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);


                    Bundle bundle = new Bundle();
                    bundle.putInt(OrderAllActivity.POSITION_KEY, 4);
                    startActivity(new Intent(RefundActivity.this, OrderAllActivity.class).putExtras(bundle));
                } else if (commenBean.getCode() == 400) {
//                    startActivity(new Intent(RefundActivity.this, SettingsPasswordActivity.class));
                    LovelyToast.makeText(RefundActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);

                } else {
                    LovelyToast.makeText(RefundActivity.this, commenBean.getMessage(), 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }


        ).execute(RefundActivity.this, false);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

    @Override
    public void onRefresh(Integer integer) {

    }
}
